package analyse

import (
	"github.com/gofiber/fiber/v2"
	"sg-backend/global"
	"sg-backend/model/paylog"
	"sg-backend/utils"
)

type _dataJson struct {
	XData  []any `json:"xData"`
	YData1 []any `json:"yData1"`
	YData2 []any `json:"yData2"`
}

// 获取本周内，每一天的收入和支出汇总，展示条形图

func GetThisWeekPayAndIncomeData(ctx *fiber.Ctx) error {
	// 获取本周开始，结束日期
	dayList := []int{1, 2, 3, 4, 5, 6, 7}

	// X轴
	xData := []any{"周一", "周二", "周三", "周四", "周五", "周六", "周日"}
	// 支出Y轴
	var yData1 []any
	for _, v := range dayList {
		startTime, endTime := utils.WeekDaysStartAndEnd(v)
		var paymentLog []paylog.PayLog
		if err := global.DB.Where("user_id = ?", global.AuthUser.UserId).
			Where("time >= ? AND time <= ?", startTime, endTime).
			Find(&paymentLog); err.Error != nil {
			return ctx.JSON(fiber.Map{
				"status":  "error",
				"message": "获取本周支出数据出错！" + err.Error.Error(),
			})
		}

		// 汇总
		var total = float64(0)
		for _, x := range paymentLog {
			total = total + x.Money - x.Refund // 减去退款才是真的支出
		}
		total = utils.NumberToStr(total)
		yData1 = append(yData1, total)
	}

	// 收入Y轴
	var yData2 []any
	for _, v := range dayList {
		startTime, endTime := utils.WeekDaysStartAndEnd(v)
		var incomeLog []paylog.IncomeLog
		if err := global.DB.Where("user_id = ?", global.AuthUser.UserId).
			Where("time >= ? AND time <= ?", startTime, endTime).
			Find(&incomeLog); err.Error != nil {
			return ctx.JSON(fiber.Map{
				"status":  "error",
				"message": "获取本周收入数据出错！" + err.Error.Error(),
			})
		}

		// 汇总
		var total = float64(0)
		for _, x := range incomeLog {
			total = total + x.Money
		}
		total = utils.NumberToStr(total)
		yData2 = append(yData2, total)
	}

	return ctx.JSON(fiber.Map{
		"status": "done",
		"data": _dataJson{
			XData:  xData,
			YData1: yData1,
			YData2: yData2,
		},
	})
}
